package com.zkc.controller;

import com.zkc.pojo.Book;
import com.zkc.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

/**
 * book的controller
 * @author Lucky
 * @date 2020/06/26
 */
@RequestMapping("/book")
@Controller
public class BookController {

    @Autowired
    private BookService bookService;
    /**
     * 查询所有的书籍
     * @return 前端的页面的字符串
     */
    @RequestMapping("allBook")
    public String queryAllBooks(Model model) {
        List<Book> books = bookService.queryAllBook();
        model.addAttribute("list",books);
        return "allbooks";
    }

    /**
     * 跳转到新增书籍页面
     * @return
     */
    @RequestMapping("/addBookPage")
    public String addBookPage() {
        return "addBook";
    }

    /**
     * 新增书籍操作
     * @return
     */
    @RequestMapping("addBook")
    public String addBook(Book book){
        System.out.println("book------" + book);
        bookService.addBook(book);
        return "redirect:/book/allBook";
    }

    /**
     * 跳转到修改书籍页面
     * @return
     */
    @RequestMapping("/updateBookPage")
    public String updateBookPage(int bookid,Model model) {
        System.out.println("bookid=====" + bookid);
        Book book = bookService.queryBookById(bookid);
        model.addAttribute("book",book);
        return "updateBook";
    }
    /**
     * 修改书籍操作
     * @return
     */
    @RequestMapping("updateBook")
    public String updateBook(Book book){
        System.out.println("book------" + book);
        bookService.updateBook(book);
        return "redirect:/book/allBook";
    }

    /**
     * 删除书籍操作
     * @return
     */
    @RequestMapping("deleteBook/{bookid}")
    public String deleteBook(@PathVariable("bookid") int bookid){
        System.out.println("bookid------" + bookid);
        bookService.deleteBookById(bookid);
        return "redirect:/book/allBook";
    }

    /**
     * 删除书籍操作
     * @return
     */
    @RequestMapping("queryBookByName")
    public String queryBookByName(String bookname,Model model) {
        String bookName = null;
        if(!StringUtils.isEmpty(bookname)){
            bookName = "%" + bookname+ "%";
        }
        List<Book> books =bookService.queryBookByName(bookName);
        if (CollectionUtils.isEmpty(books)) {
            model.addAttribute("error","未查询到数据");
        }
        model.addAttribute("list",books);
        return "allbooks";
    }
}
